package navigation.wzg.com.navigation.activities;

//写日记

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import navigation.wzg.com.navigation.MainActivity;
import navigation.wzg.com.navigation.R;
import navigation.wzg.com.navigation.Soaked.Soaked;
import navigation.wzg.com.navigation.animation.Anim;
import navigation.wzg.com.navigation.db.Diary;
import navigation.wzg.com.navigation.db.greendao.DiaryDao;
import navigation.wzg.com.navigation.vo.AFaApplication;

public class Operation_diary extends AppCompatActivity {

    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.kk)
    LinearLayout kk;
    @BindView(R.id.ok)
    Button ok;
//    @BindView(R.id.text)
//    EditText text;
    static EditText text;

    String date;
    @BindView(R.id.write_image)
    Button writeImage;
    @BindView(R.id.album_button)
    Button albumButton;
    @BindView(R.id.camera_button)
    Button cameraButton;
    @BindView(R.id.activity_operation_diary)
    LinearLayout activityOperationDiary;
    @BindView(R.id.AddImageLY)
    LinearLayout AddImageLY;
    @BindView(R.id.coloer_button)
    Button coloerButton;
    private DiaryDao dao;
    boolean image = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_operation_diary);
        dao = AFaApplication.getApplication().getDaoSession().getDiaryDao();
        ButterKnife.bind(this);
        Soaked.initState(this, kk);

        text = (EditText) findViewById(R.id.textss);
/**
 *获取本地时间，将其放入toolbar中
 */
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        date = sDateFormat.format(new Date());
        mainToolbar.setTitle(date);
        setSupportActionBar(mainToolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        mainToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updatelist();
            }
        });
    }

    /**
     * 监听返回事件
     */
    public void onBackPressed() {
        if (!image) {
            AddImageLY.setVisibility(View.GONE);
            image = true;
        } else {
            if (text.getText().toString().length() > 0) {
                new AlertDialog.Builder(this)
                        .setTitle("通知：")
                        .setMessage("是否保存未完成项目？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                updatelist();
                            }
                        })
                        .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                insertData();
                                Toast.makeText(Operation_diary.this, "保存成功！", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .show();
            } else {
                updatelist();
            }
        }

    }

    @OnClick(R.id.ok)
    public void onViewClicked() {
        insertData();
        Toast.makeText(this, "保存成功！", Toast.LENGTH_SHORT).show();
    }

    public void insertData() {
        String abc = text.getText().toString();
        String str = abc;
        if (abc.length() > 15) {
            str = str.substring(0, 15);
        }
        String time = date;
        String end;
        if (abc.length() <= 15) {
            end = "";
        } else {
            end = "...";
        }
        String title = str + end;
        String matter = abc;
        if (matter.length() == 0) {
            Toast.makeText(this, "请不要保存空的日记", Toast.LENGTH_SHORT).show();
        } else {
            Diary insertData = new Diary(null, time, title, matter);
            dao.insert(insertData);
            Toast.makeText(this, "保存完成", Toast.LENGTH_SHORT).show();
            updatelist();
        }
    }


    //刷新Listview
    public void updatelist() {
        startActivity(new Intent(Operation_diary.this, MainActivity.class));
        finish();
        overridePendingTransition(R.anim.out, R.anim.up);
    }

    @OnClick({R.id.write_image, R.id.album_button, R.id.camera_button,R.id.coloer_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.write_image:
                if (image) {
                    AddImageLY.setVisibility(View.VISIBLE);
                    Anim.setretote(findViewById(R.id.write_image));
                    image = false;
                } else {
                    AddImageLY.setVisibility(View.GONE);
                    Anim.setretote(findViewById(R.id.write_image));
                    image = true;
                }
                break;
            case R.id.album_button:
                Intent intent;
                //添加图片的主要代码
                intent = new Intent();
                //设定类型为image
                intent.setType("image/*");
                //设置action
                intent.setAction(Intent.ACTION_GET_CONTENT);
                //选中相片后返回本Activity
                startActivityForResult(intent, 1);
                break;
            case R.id.camera_button:
//                Intent intent;
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//区分选择相片
                startActivityForResult(intent, 2);
                break;
            case R.id.coloer_button:
                Intent intents = new Intent();
                intents.setClass(Operation_diary.this, Colorfont.class);
                Bundle bundle = new Bundle();
                bundle.putString("matter", text.getText().toString());
                intents.putExtras(bundle);
                startActivity(intents);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Uri uri;
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            //取得数据
            uri = data.getData();
            ContentResolver cr = Operation_diary.this.getContentResolver();
            Bitmap bitmap = null;
            Bundle extras = null;
            //如果是选择照片
            if (requestCode == 1) {

                try {
                    //将对象存入Bitmap中
                    bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //如果选择的是拍照
            else if (requestCode == 2) {
                System.out.println("-----fjwefowefwef");
                try {
                    if (uri != null)
                        //这个方法是根据Uri获取Bitmap图片的静态方法
                        bitmap = MediaStore.Images.Media.getBitmap(cr, uri);
                        //这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
                    else
                        extras = data.getExtras();
                    bitmap = extras.getParcelable("data");

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            int imgWidth = bitmap.getWidth();
            int imgHeight = bitmap.getHeight();
            double partion = imgWidth * 1.0 / imgHeight;
            double sqrtLength = Math.sqrt(partion * partion + 1);
            //新的缩略图大小
            double newImgW = 480 * (partion / sqrtLength);
            double newImgH = 480 * (1 / sqrtLength);
            float scaleW = (float) (newImgW / imgWidth);
            float scaleH = (float) (newImgH / imgHeight);

            Matrix mx = new Matrix();
            //对原图片进行缩放
            mx.postScale(scaleW, scaleH);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, imgWidth, imgHeight, mx, true);
            final ImageSpan imageSpan = new ImageSpan(this, bitmap);
            SpannableString spannableString = new SpannableString("</image>"+uri+"</image>");
            spannableString.setSpan(imageSpan, 0, spannableString.length(), SpannableString.SPAN_MARK_MARK);
            //光标移到下一行
            text.append("\n");
            Editable editable = text.getEditableText();
            Toast.makeText(this, text.getText().toString(), Toast.LENGTH_SHORT).show();
            int selectionIndex = text.getSelectionStart();
            Toast.makeText(this, selectionIndex+"", Toast.LENGTH_SHORT).show();
            spannableString.getSpans(0, spannableString.length(), ImageSpan.class);

            //将图片添加进EditText中
            editable.insert(selectionIndex, spannableString);
            //添加图片后自动空出两行
            text.append("\n\n");

            AddImageLY.setVisibility(View.GONE);
            image = true;
        }
    }
}
